<?php
/**
 * ----------------------------------------------------------
 * date: 2019/6/10 8:42
 * ----------------------------------------------------------
 * author: Raoxiaoya
 * ----------------------------------------------------------
 * describe: 记录响应日志
 * ----------------------------------------------------------
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;

class ResponseLog
{

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try{

            $path = $request->path();
            if(strpos($path, 'backend/') === 0){
                //Config::set();
                Config::set('logging.channels.daily.path', storage_path('logs/backend/laravel.log'));
            } else{
                Config::set('logging.channels.daily.path', storage_path('logs/ddd/laravel.log'));
            }

            $cline    = chr(10);
            $response = $next($request);
            $return   = json_encode(json_decode($response->getContent(), 1), JSON_UNESCAPED_UNICODE).$cline;

            // 保存返回数据
            $time = (microtime(true) - LARAVEL_START) * 1000;
            $log  = 'Response | '.$request->getPathInfo().' | [RunTime:'.$time.'ms]';
            $log  .= strlen($return) <= 1000 ? ' | '.$return : '';
            /*if(strlen($return) <= 1000){
                Log::debug('Response | '.$request->getPathInfo().' | '.$return);
            }*/
            Log::debug($log);
            //Log::useFiles(storage_path('logs/zabbix/error.log'));

            // 未获取到sql
            /*DB::listen(
                function ($sql) {
                    var_dump($sql);
                    file_put_contents(public_path().'/sql.log',$sql.'['.print_r($param, 1).']'."\r\n",8);
                }
            );*/
            // 未获取到sql
            /*Event::listen('illuminate.query', function($sql,$param) {
                var_dump($sql);
            });*/
            //(new \vendor\laravel\framework\src\Illuminate\Database\Query())->toSql();


            // 保存sql语句到日志中
            $queries = DB::getQueryLog();
            foreach($queries as $query){
                $sql = str_replace('?', '\'%s\'', $query['query']);
                $sql = vsprintf($sql, $query['bindings']);
                $log = 'SQL: '.$sql.'; [RunTime:'.$query['time'].'ms]';
                Log::info($log);
            }

            return $response;
        } catch(\HttpException $e){
            return ['code' => $e->getStatusCode(), 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
        } catch(\Exception $e){
            return ['code' => 1, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
        }

    }
}

